
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var wxAuthFail = true; 
var score = 5;
Page({
  data: {
    albumid: '',

    userInfo: '',
    uid: '',
    token: '',
    colorSet: '',
    tc: 0,
    page: 1,
    limit: 10,
    data: [],
    hasMore: true,
    hasLoadding: false,
    noData: false,

    right_view_w: 240,
    wz_item_img_w: 100,

    latitude: 0,
    longitude: 0,

    hide_commentview: true,
    hide_pingfenview: true,

    data_id: '',
    commentValue: '',

    colorSet: '',
    pf_userid: '',
    scores: [
      { name: '1', value: '1分' },
      { name: '2', value: '2分' },
      { name: '3', value: '3分' },
      { name: '4', value: '4分' },
      { name: '5', value: '5分', checked: 'true' }
    ],

    woyaoqiuzhi: [],
    woyaozhaopin: [],

    editid: '',

    cataArray: [{ id: 0, title: "最新发布" },
                { id: 1, title: "最新回复" },
                { id: 2, title: "最近距离" },
                { id: 3, title: "最高点击" },
                { id: 4, title: "最多评论" },
                ],

    currentcata: 0,
    currcata: 0,
  },

  onLoad: function (options) {
    console.log("所有数据列表：", options);
    wx.setNavigationBarTitle({
      title: options.title,
    })
    var that = this;
    
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
    });

    wx.getSystemInfo({
      success: function (res) {
        var wid = (res.windowWidth - 79) / 3;
        that.setData({
          right_view_w: res.windowWidth - 73,
          wz_item_img_w: wid,
          tc: app.get_tc(),
          albumid: options.albumid ? options.albumid : ''
        })
      }
    })

    this.getLoginInfo();

    //获取定位
    this.getMyLocation();
  },

  load: function (refresh) {
    this.setData({
      hasLoadding: true,
    });
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
    });
    var dataType = this.data.topicType;
    var page = that.data.page;
    var num = that.data.limit;
    if(refresh && that.data.data.length > 0){
      page = 1;
      num = that.data.data.length;
      that.setData({
        page: page
      })
    }
    util.api({
      data: {
        publickey: util.publiccode,
        // ac: "topiclist",
        ac: "topiclistverified",
        orgid: util.orgid,
        topictype: 1,
        albumid: (that.data.albumid == 14 || that.data.albumid == 27) ? '' : that.data.albumid,
        // toporder: 1,
        verified: 1,
        page: page,
        num: num
      },
      success: function (responseData) {
        console.log("所有数据列表：", responseData);
        var data = responseData.data;
        var newData;
        if (data && !data.msg) {
          for (var i = 0; i < data.length; i++) {
            data[i].message = app.parseHTMLText(data[i].message);
            var date = new Date(data[i].dateline * 1000);
            data[i].formattime = util.formatTime(date, '-', ':');
            //处理用户等级
            var level = 0;
            var num = data[i].user.scorenum
            data[i].user.level = 0;
            data[i].user.junfen = 0;
            if(num > 0){
              var fen = data[i].user.scorecoin;
              var junfen = (fen / num).toFixed(1);
              if(junfen >= 4){
                if(num >= 10000){
                  level == 5;
                } else if(num >= 5000){
                  level == 4;
                } else if (num >= 3000) {
                  level == 3;
                } else if (num >= 500) {
                  level == 2;
                } else if(num >= 100){
                  level == 1;
                }
              } else if(junfen >= 3){
                if (num >= 10000) {
                  level == 4;
                } else if (num >= 5000) {
                  level == 3;
                } else if (num >= 3000) {
                  level == 2;
                } else if (num >= 100){
                  level == 1;
                }
              } else if (junfen >= 2) {
                if (num >= 10000) {
                  level == 3;
                } else if (num >= 5000) {
                  level == 2;
                } else if (num >= 100){
                  level == 1;
                }
              } else{
                if (num >= 10000) {
                  level == 2;
                } else if (num >= 100){
                  level == 1;
                }
              }

              data[i].user.level = level;
              data[i].user.junfen = junfen;
            }
            if (that.data.latitude){
              //计算直线距离
              var distanStr = '';
              var distan = app.getDistance(that.data.latitude, that.data.longitude, data[i].lat, data[i].lon);
              if(distan > 1000){
                distanStr = (distan/1000).toFixed(2) + 'km';
              } else {
                distanStr = distan.toFixed(0) + 'm';
              }

              data[i].distanse = distanStr;
              data[i].distansenum = distan;
            }
            //处评论者信息
            var peoples = data[i].people;
            var comments = data[i].comments;
            for(var j = 0; j < comments.length; j++){
              var commentUserId = comments[j].author.uid;
              if(peoples.indexOf(commentUserId) >= 0){
                commrents[j].buied = true;
              }
            }
          }
          if(refresh){
            newData = data
          } else {
            newData = that.data.data.concat(data);
          }

          newData.sort(that.comparator);
          console.log("=======:", newData);

          var woyaoqiuzhi = [];
          var woyaozhaopin = [];
          for (var i = 0; i < newData.length; i++) {

            if (newData[i]['albumid'] == '13') {
              woyaoqiuzhi.push(newData[i]);
            } else if (newData[i]['albumid'] == '14') {
              woyaozhaopin.push(newData[i]);
            }
            if(that.data.albumid==14){
              if (newData[i].address.indexOf("怀集") < 0) {
                console.log("非怀集", newData[i].address)
                newData.splice(i,1);
                i--;
                console.log("怀集过滤")
              }
            }
            if (that.data.albumid == 27) {
              if (newData[i].address.indexOf("怀集") >= 0) {
                console.log("是怀集", newData[i].address)
                newData.splice(i, 1);
                i--;
                console.log("外地过滤")
              }
            }


          }

          that.setData({
            data: newData,
            hasLoadding: false,
            woyaoqiuzhi: woyaoqiuzhi,
            woyaozhaopin: woyaozhaopin

          });
        } else {
          that.setData({
            hasMore: false
          });
        }
        if (that.data.data.length <= 0) {
          that.setData({
            noData: true
          })
        }
        wx.hideLoading();
      }
    });


  },
  loadMore: function () {
    var page;
    if (this.data.hasMore && !this.data.hasLoadding) {
      page = this.data.page;
      this.setData({
        page: ++page
      });
      this.load(false);
    }
  },

  getLoginInfo: function () {
    var that = this;
    app.LoginUserInfo(function (res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1;//用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        userInfo: res,
        uid: res.uid,
        token: res.token
      });
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },

  goAtherPage: function (e) {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
    } else {
      var url = e.currentTarget.dataset.link;
      wx.navigateTo({ url: url })
    }
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },

  showCommentView: function(e){
    this.setData({
      hide_commentview: false,
      data_id: e.currentTarget.dataset.id
    })
  },
  hideCommentView: function () {
    this.setData({
      hide_commentview: true
    })
  },

  inputFinish: function(e){
    var comment = e.detail.value;
    console.log("输入信息：" + comment);
    this.setData({
      commentValue: comment
    })
  },

  addComment: function (e) {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

    wx.showLoading({
      title: '...',
      mask: 'true'
    })

    var that = this;
    var message = that.data.commentValue;
    if (!message) {
      app.dialog('请输入内容', 'loading');
      return;
    }

    var uid = that.data.uid;
    var token = that.data.token;
    var topicid = that.data.data_id;
    var replyid = '';
    
    var privatekey = utilMd5.hexMD5(uid + 'topiccomment' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiccomment",
        uid: uid,
        id: topicid,
        'type': 1,
        replyid: replyid,
        message: message,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        if (data.msg === "true") {
          that.setData({
            commentValue: '',
            hide_commentview: true
          })
          that.load(true);
        } else {
          wx.showToast({
            title: data.msg,
          })
        }
        wx.hideLoading();
      }
    });
  },

  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  //获取定位信息
  getMyLocation: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log("定位信息：", res);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        that.load(true);
      },
      fail: function () {
        wx.showModal({
          title: '提示',
          content: '获取定位信息失败，这将影响您的使用体验，是否重新设置授权？',
          showCancel: true,
          cancelText: "否",
          confirmText: "是",
          success: function (res) {
            if (res.confirm) {
              wx.OpenSetting({
                success: function (res) {
                  console.log(res);
                  console.log('success');
                  that.getMyLocation();
                },
                fail: function () {
                  console.log('fail');
                }
              })
            } else if (res.cancel) {
              console.log('用户点击否')
              that.load(true);
            }
          }
        })
      }
    })
  },

  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },

  buyForHim: function(e){
    
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

    var that = this;
    
    var uid = that.data.uid;
    var token = that.data.token;
    var topicid = e.currentTarget.dataset.id;
    var privatekey = utilMd5.hexMD5(uid + 'addpeople' + token);

    var dataIndex = e.currentTarget.dataset.index;

    util.api({
      data: {
        ac: "addpeople",
        uid: uid,
        topicid: topicid,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("帮他买：", data);
        if(data.res){
          var allData = that.data.data;
          var data = allData[dataIndex];
          data.peopleinfo.push(that.data.userInfo);
          that.setData({
            data: allData
          })
          console.log("刷新后的数据：", that.data.data);
        }
        wx.hideLoading();
      }
    });
  },

  showPingfenView: function (e) {
    this.setData({
      hide_pingfenview: false,
      pf_userid: e.currentTarget.dataset.uid
    })
  },
  hidePingfenView: function () {
    this.setData({
      hide_pingfenview: true
    })
  },
  scoreChange: function (e) {
    score = e.detail.value;
  },
  sendPingfen: function(){
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

    var that = this;

    var uid = that.data.uid;
    var token = that.data.token;
    var privatekey = utilMd5.hexMD5(uid + 'postuserscore' + token);

    util.api({
      data: {
        ac: "postuserscore",
        uid: that.data.pf_userid,
        postuid: uid,
        score: score,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("评分：", data);
        that.hidePingfenView();
        if (data.res) {
          wx.showToast({
            title: '评分成功',
            icon: 'success',
            duration: 1000
          })
        }
        wx.hideLoading();
      }
    });
  },
  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

  },
  showEWM: function (e) {
    console.log(e);
    var src = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + src);
    var list = e.currentTarget.dataset.list;//获取data-list
    console.log("图片列表:" + list);

    var option = JSON.stringify(list);
    var array = JSON.parse(option);
    console.log("array", array);
    var imgList = [];
    for (var i = 0; i < array.length; i++) {
      imgList.push(array[i]['photo']);
    }
    console.log("imgList", imgList);
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })


  },


  //点击确定
  queding: function (e) {
    var id = e.target.dataset.uid;
    var catatype = e.target.dataset.catatype;
    console.log(id);
    var that = this;
    that.setData({
      quedingShow: true,
      editid: id,
      catatype: catatype,

    })
  },
  //隐藏拒绝列表
  hidequeding: function () {
    this.setData({
      quedingShow: false
    })
  },

  //应聘接口
  yingpin: function (e) {
    console.log(e);

    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + 'mianshi' + that.data.token);
    util.api({
      method: "post",
      data: {
        ac: "mianshi",
        uid: that.data.uid,
        privatekey: privatekey,
        username: that.data.userInfo.uname,
        phone: that.data.userInfo.phone,
        fabuzheuid: that.data.editid,
        type: e.target.dataset.type,
        catatype: that.data.catatype

      },
      success: function (responseData) {
        console.log("调试--预约接口接口:", responseData.data);
        if (responseData.data.res == true) {
          var contentname = this.data.tc == 1 ? '已成功預約' : '已成功预约';
          app.dialogToast(contentname, "success", function () {
            wx.reLaunch({ url: '/pages/mine/mine' });
          });
        } else {
          var contentname = this.data.tc == 1 ? '預約失败' : '预约失败';
          wx.showToast({
            title: contentname,
          })
        }
      }
    });
  },

  changeCata: function (e) {
    console.log(e.currentTarget.dataset.cataid);
    var cataid = e.currentTarget.dataset.cataid;
    var cataindex = e.currentTarget.dataset.index;
    this.setData({
      currentcata: cataid,
      currcata: cataindex,
    })
    this.load(true);
    console.log(cataid, cataindex);
  },

  comparator: function (a, b) {
    console.log(" comparator")
    if (this.data.currentcata == 2) {
      return a.distansenum - b.distansenum;

    } else if (this.data.currentcata == 1) {
      var timeofb = b.dateline;
      var timeofa = a.dateline;
      if (b.comments.length > 0) {
        timeofb = b.comments[0].dateline;
      }
      if (a.comments.length > 0) {
        timeofa = a.comments[0].dateline;
      }

      return timeofb - timeofa;
    } else if (this.data.currentcata == 0) {
      return b.dateline - a.dateline;
    } else if (this.data.currentcata == 3) {
      return b.clicknum - a.clicknum;
    } else if (this.data.currentcata == 4) {
      return b.commentnum - a.commentnum;
    }

  }
})